<!-- views/Register.vue  -->
<template>
  <div class="register-container tree-bg">
    <div class="register-box">
      <div class="tree-logo">
        <img src="@/assets/image/tree-logo.jpg" alt="树木Logo">
        <h2>加入森林</h2>
      </div>

      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" prefix-icon="el-icon-mobile-phone">
          </el-input>
        </el-form-item>

        <el-form-item prop="captcha">
          <div class="code-input">
            <el-input v-model="form.captcha" placeholder="请输入验证码" prefix-icon="el-icon-message">
            </el-input>
            <el-button :disabled="isCounting" @click="getSmsCode" class="code-btn">
              {{ codeBtnText }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" placeholder="请设置登录密码" prefix-icon="el-icon-lock"
            show-password>
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input v-model="form.confirmPassword" type="password" placeholder="请确认密码" prefix-icon="el-icon-lock"
            show-password>
          </el-input>
        </el-form-item>
      </el-form>

      <el-button type="primary" class="register-btn" @click="handleRegister" :loading="loading">
        立即注册
      </el-button>

      <div class="register-footer">
        <span @click="gotoLogin">已有账号？立即登录</span>
        <span class="leaf-divider">
          <img src="@/assets/image/leaf.jpg" alt="树叶装饰">
        </span>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormRules, FormInstance } from 'element-plus'
/* import type { InternalRuleItem } from 'async-validator'
import type { FormValidateCallback } from 'element-plus' */

import type { InternalRuleItem } from 'async-validator'
import { sendCaptcha, userRegister } from '@/api/user'

const router = useRouter()

// 注册表单
const form = reactive({
  phone: '',
  captcha: '',
  password: '',
  confirmPassword: ''
})

// 验证规则

/* const validatePass = (rule: FormItemRule, value: string, callback: (error?: Error) => void) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}
 */

const validatePass = (
  rule: InternalRuleItem,
  value: string,
  callback: (error?: string | Error | undefined) => void,

) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}



const rules = reactive<FormRules>({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass, trigger: 'blur' }
  ]
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const isCounting = ref(false)
const codeBtnText = ref('获取验证码')
let countdown = 6

// 获取验证码
const getSmsCode = async () => {
  try {
    await formRef.value?.validateField('phone')
    isCounting.value = true

    const result = await sendCaptcha(form.phone)
    if (result.code === 1) {
      ElMessage.success(' 验证码已发送')
      startCountdown()
    } else {
      ElMessage.error(result.msg || '验证码发送失败')
      resetCodeButton()
    }
  } catch (error) {
    console.error(' 验证码请求失败:', error)
    resetCodeButton()
    ElMessage.error(' 验证码发送异常')
  }
}

// 倒计时逻辑
const startCountdown = () => {
  const timer = setInterval(() => {
    countdown--
    codeBtnText.value = `${countdown}s后重新获取`
    if (countdown <= 0) {
      clearInterval(timer)
      resetCodeButton()
    }
  }, 1000)
}

// 重置验证码按钮状态
const resetCodeButton = () => {
  isCounting.value = false
  codeBtnText.value = '获取验证码'
  countdown = 60
}
// 注册处理
const handleRegister = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return // 验证失败直接返回

    try {
      loading.value = true

      // 1. 调用注册接口
      const result = await userRegister({
        phone: form.phone,
        captcha: form.captcha,
        password: form.password
        // 注意：confirmPassword通常不传给后端
      })

      // 2. 处理注册结果
      if (result.code === 1) {
        ElMessage.success(' 注册成功')

        /*   // 3. 自动登录（可选）
          const tokenStore = useTokenStore()
          tokenStore.setUserInfo({
            username: form.phone,  // 或使用后端返回的用户名
            avatar: '',
            token: result.data.token  // 假设返回token
          }) */

        // 4. 跳转到登录页或首页
        router.push('/login')
      } else {
        ElMessage.error(result.msg || '注册失败')
        form.captcha = ''
      }
    } catch (error) {
      console.error(' 注册异常:', error)
      ElMessage.error(' 网络请求失败')
    } finally {
      loading.value = false
    }
  })
}

// 跳转登录页
const gotoLogin = () => {
  router.push('/login')
}
</script>

<style lang="scss" scoped>
.register-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;

  &.tree-bg {
    background-image: url('@/assets/tree-bg-dark.jpg');
    background-size: cover;
    background-position: center;
  }
}

.register-box {
  width: 400px;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  border: 1px solid #e8e8e8;
}

.tree-logo {
  text-align: center;
  margin-bottom: 30px;

  img {
    width: 80px;
    height: 80px;
  }

  h2 {
    margin-top: 10px;
    color: #3a7d34;
    font-weight: 500;
  }
}

.code-input {
  display: flex;

  .el-input {
    flex: 1;
  }

  .code-btn {
    margin-left: 10px;
    width: 120px;
  }
}

.register-btn {
  width: 100%;
  margin-top: 20px;
  background-color: #3a7d34;
  border-color: #3a7d34;
  font-size: 16px;
  height: 45px;

  &:hover {
    background-color: #4d9c46;
    border-color: #4d9c46;
  }
}

.register-footer {
  margin-top: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;

  span {
    cursor: pointer;
    transition: color 0.3s;

    &:hover {
      color: #3a7d34;
    }
  }

  .leaf-divider {
    display: inline-block;
    margin: 0 15px;

    img {
      width: 16px;
      height: 16px;
      vertical-align: middle;
    }
  }
}
</style>
